﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SiteApp.BLL.Common;
using SiteApp.BLL.Interface;
using SiteApp.DAL;
using SiteApp.Web.Model;
using System;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SiteApp.Web.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ClientController : ControllerBase
    {



        private readonly IPointForTemperatureService temperature = null;
        private readonly IPointForSF6Service sf6 = null;
        private readonly IPointForInfraredService infrared = null;
        private readonly INewInfraredService newInfrared = null;
        private readonly INewInfraredDetailService newInfraredDetail = null;
        private readonly ILogger<ClientController> _logger;
        private bool IsValid()
        {
            if (HttpContext.User.Claims.ToList() != null && HttpContext.User.Claims.ToList()[0].Type == "IsAuthenticated" && HttpContext.User.Claims.ToList()[0].Value == "true")
            {
                return true;
            }
            return false;
        }



        public ClientController(
             IPointForTemperatureService _temperature,
             IPointForSF6Service _sf6,
             ILogger<ClientController> logger,
             IPointForInfraredService _infrared,
             INewInfraredService _newInfrared,
             INewInfraredDetailService _newInfraredDetail)
        {
            this.temperature = _temperature;
            this.sf6 = _sf6;
            _logger = logger;
            this.infrared = _infrared;
            this.newInfrared = _newInfrared;
            this.newInfraredDetail = _newInfraredDetail;
        }

        /// <summary>
        /// 温湿度接口收集
        /// </summary>
        [HttpPost]
        [Route("TemperatureAccept")]
        public async Task<JsonResult> TemperatureAccept()
        {
            _logger.LogInformation("温湿度接口开始接受数据");
            var json = string.Empty;
            if (Request.Form != null && Request.Form.Keys.Count() > 0)
            {
                json = Request.Form.Keys.ToList()[0].ToString();
                _logger.LogInformation("温湿度json" + json);
            }

      
            var result = new WebResult();

            if (!string.IsNullOrWhiteSpace(json) && IsValid())
            {
                var jsonEntity = new TemperatureModel();

                //#region    work Service 序列化的json 反序列化，死活报错。拎到json.cn都能直接解析。沙雕 Newtonsoft.Json
                ////请求报文,因为它不能直接读。所以存记事本在取出来
                //// ﻿{"Name":"Name","Code":"Code","Temperature":"Temperature","Humidity":"Humidity","Time":"Time"} 


                //FileStream stream = new FileStream($"{System.AppDomain.CurrentDomain.BaseDirectory}Json.txt", FileMode.CreateNew);
                //StreamWriter writer = new StreamWriter(stream);
                //writer.WriteLine(json);//写入一行，写完后会自动换行

                //writer.Close();//释放内存
                //stream.Close();//释放内存


                //FileStream streamRead = new FileStream($"{System.AppDomain.CurrentDomain.BaseDirectory}\\Json.txt", FileMode.Open);
                //StreamReader reader = new StreamReader(streamRead);

                //json = reader.ReadToEnd();  //一次性读取全部数据
                //reader.Close();
                //streamRead.Close();

                //#endregion

                jsonEntity = JsonConvert.DeserializeObject<TemperatureModel>(json);
               
                temperature.InsertPointForTemperature(new SiteApp.Model.PointForTemperature
                {
                    PointId = jsonEntity.Code,
                    CREATETIME = Convert.ToDateTime(jsonEntity.Time),
                    Temperature = jsonEntity.Temperature,
                    Humidity = jsonEntity.Humidity,
                    SiteId=jsonEntity.SiteId

                });


            }
            _logger.LogInformation("温湿度接口结束接受数据");
            return new JsonResult(result);
        }


        /// <summary>
        /// SF6接口收集
        /// </summary>
        [HttpPost]
        [Route("SF6Accept")]
        public async Task<JsonResult> SF6Accept()
        {
            _logger.LogInformation("SF6接口开始接受数据");
            var json = string.Empty;
            if (Request.Form != null && Request.Form.Keys.Count() > 0)
            {
                json = Request.Form.Keys.ToList()[0].ToString();
                _logger.LogInformation("SF6json" + json);
            }

            var result = new WebResult();

            //#region    work Service 序列化的json 反序列化，死活报错。拎到json.cn都能直接解析。沙雕 Newtonsoft.Json
            ////请求报文,因为它不能直接读。所以存记事本在取出来
            //// ﻿{"Id":0,"Time":"4","Pressure":"2","Moisture":"3","TableName":"1"}


            //FileStream stream = new FileStream($"{System.AppDomain.CurrentDomain.BaseDirectory}SF6Json.txt", FileMode.Truncate);
            //StreamWriter writer = new StreamWriter(stream);
            //writer.WriteLine(json);//写入一行，写完后会自动换行

            //writer.Close();//释放内存
            //stream.Close();//释放内存


            //FileStream streamRead = new FileStream($"{System.AppDomain.CurrentDomain.BaseDirectory}SF6Json.txt", FileMode.Open);
            //StreamReader reader = new StreamReader(streamRead);

            //json = reader.ReadToEnd();  //一次性读取全部数据
            //reader.Close();
            //streamRead.Close();

            //#endregion



            if (!string.IsNullOrWhiteSpace(json) && IsValid())
            {
                var jsonEntity = JsonConvert.DeserializeObject<SF6Model>(json);

                sf6.InsertPointForSF6(new SiteApp.Model.PointForSF6
                {
                    PointId = jsonEntity.TableName,
                    CREATETIME = Convert.ToDateTime(jsonEntity.Time),
                    Pressure = jsonEntity.Pressure,
                    Moisture = jsonEntity.Moisture,
                    SiteId=jsonEntity.SiteId

                });


            }

            _logger.LogInformation("SF6接口结束接受数据");
            return new JsonResult(result);
        }


        /// <summary>
        /// 老红外图片上传
        /// </summary>
        [HttpPost]
        [Route("InfraredImg")]
        public async Task<JsonResult> InfraredImg()
        {
            var result ="-1";
            if (IsValid())
            {
                try
                {
                    var files = Request.Form.Files;
                    if (files != null)
                    {
                        var file = files[0];

                        var location = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\" + file.FileName;

                        if (!Directory.Exists(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\")) //判断上传文件夹是否存在，若不存在，则创建
                        {
                            Directory.CreateDirectory(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\"); //创建文件夹
                        }

                        using (var stream = new FileStream(location, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                            result = $"{Request.Scheme}://{Request.Host.Value}/Image/{file.FileName}";
                        }
                    }
                }
                catch (Exception e)
                {

                    throw;
                }
            }
            return new JsonResult(result);

        }

        /// <summary>
        /// 老红外图片信息收集
        /// </summary>
        [HttpPost]
        [Route("InfraredAccept")]
        public async Task<JsonResult> InfraredAccept()
        {
            _logger.LogInformation("老红外接口开始接受数据");
            var json = string.Empty;
            if (Request.Form != null && Request.Form.Keys.Count() > 0)
            {
                json = Request.Form.Keys.ToList()[0].ToString();
                _logger.LogInformation("老红外接口Json:" + json);
            }

            var result = new WebResult();

            if (!string.IsNullOrWhiteSpace(json) && IsValid())
            {
                var jsonEntity = JsonConvert.DeserializeObject<InfraredModel>(json);

                infrared.InsertPointForInfrared(new SiteApp.Model.PointForInfrared
                {
                  
                    PointId=jsonEntity.PointId,
                    Img=jsonEntity.Img,
                    CREATETIME =Convert.ToDateTime(jsonEntity.Createtime),
                    SiteId =jsonEntity.SiteId
                });


            }

            _logger.LogInformation("老红外接口结束接受数据");
            return new JsonResult(result);
        }



        /// <summary>
        /// 新红外接口收集
        /// </summary>
        [HttpPost]
        [Route("NewInfraredAccept")]
        public async Task<JsonResult> NewInfraredAccept()
        {
            _logger.LogInformation("新红外接口开始接受数据");
            var result = new WebResult();
            result.Data = -1;
            if (IsValid())
            {
                try
                {
                    using (var reader = new StreamReader(Request.Body))//从身体里读取
                    {

                        var body = await reader.ReadToEndAsync();

                        _logger.LogInformation("新红外json" + body);

                        #region 用于测试

                        //FileStream streamRead = new FileStream(@$"C:\Users\newYear\Desktop\报警.txt", FileMode.Open);
                        //StreamReader reader2 = new StreamReader(streamRead);

                        //body = reader2.ReadToEnd();  //一次性读取全部数据
                        //reader2.Close();
                        //streamRead.Close();

                        #endregion


                        var entity = JsonConvert.DeserializeObject<NewInfraredModel>(body);

                        //"data:image/jpeg;base64," + entity.ImgBase64;//给前端image 使用

                        #region 处理图片温度一维数组

                        byte[] base64arr = Convert.FromBase64String(entity.AllTemp);

                        string resultString = string.Empty;
                        using (MemoryStream ms = new MemoryStream(base64arr))
                        {
                            using (GZipStream decompressedStream = new GZipStream(ms, CompressionMode.Decompress))
                            {
                                using (StreamReader sr = new StreamReader(decompressedStream, Encoding.Default))
                                {
                                    resultString = sr.ReadToEnd();
                                }
                            }
                        }


                        #endregion

                        #region 存放图片


                        var img = ImageHelper.Base64StrToImage(entity.ImgBase64);

                        Bitmap bm2 = new Bitmap(img.Width, img.Height);
                        Graphics g = Graphics.FromImage(bm2);
                        g.DrawImageUnscaled(img, 0, 0);
                        g.Dispose();
                        bm2.Save($"{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Image\\{ entity.TempId}.jpg",
                        System.Drawing.Imaging.ImageFormat.Jpeg);


                        var imgAddress=$"{AppConfigurtaionServices.Configuration.GetSection("Img").Value}{entity.TempId}.jpg";

                        #endregion


                        result.Data = newInfrared.InsertNewInfrared(new SiteApp.Model.NewInfrared { 
                        TempId= entity.TempId,
                            PointName=entity.PointName,
                            DeviceSn=entity.DeviceSn,
                            Time=entity.Time,
                            IsAlarm=entity.IsAlarm,
                            ImgBase64= imgAddress,
                            AllTemp= resultString,
                            AlarmMsg= entity.AlarmMsg,
                            CREATETIME=DateTime.Now
                        });

                        for (int i = 0; i < entity.ListTemp.Count; i++)
                        {
                            newInfraredDetail.InsertNewInfraredDetails(new SiteApp.Model.NewInfraredDetails {
                                //TempId,ToolType,ToolName,PtStart,PtEnd,PtPoly,Max,Min,Avg,Alarm,IsAlarm,Pahse,Part,Summary,CREATETIME
                                TempId=entity.TempId,
                                ToolType= entity.ListTemp[i].ToolType,
                                ToolName= entity.ListTemp[i].ToolName,
                                PtStart=entity.ListTemp[i].PtStart,
                                PtEnd= entity.ListTemp[i].PtEnd,
                                PtPoly = entity.ListTemp[i].PtPoly,
                                Max = entity.ListTemp[i].Max,
                                Min = entity.ListTemp[i].Min,
                                Avg = entity.ListTemp[i].Avg,
                                Alarm = entity.ListTemp[i].Alarm,
                                IsAlarm = entity.ListTemp[i].IsAlarm,
                                Pahse = entity.ListTemp[i].Pahse,
                                Part = entity.ListTemp[i].Part,
                                Summary = entity.ListTemp[i].Summary,
                                CREATETIME =DateTime.Now

                            });
                        }




                    }
                    result.Data = 1;

                }
                catch (Exception e)
                {

                    throw;
                }
            }
            _logger.LogInformation("新红外接口结束接受数据");
            return new JsonResult(result);

        }


        /// <summary>
        /// 新红外通信
        /// </summary>
        [HttpPost]
        [Route("Health")]
        public async Task<JsonResult> Health()
        {
           
            var result = new WebResult();
            result.Data = -1;
            if (IsValid())
            {
                try
                {
                    result.Data = 1;
                }
                catch (Exception e)
                {

                    throw;
                }
            }
            return new JsonResult(result);

        }

    }


}
